import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class Tes {

   static class User {
        private String name;

        public User(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

    }

    public static void main(String[] args) {

        //创建解析器。SpelExpressionParser是Spring内部对ExpressionParser的唯一最终实现类
        ExpressionParser parser = new SpelExpressionParser();
        EvaluationContext context = new StandardEvaluationContext();


        //例1：
        Expression exp1 = parser.parseExpression("1 + 2");
        Object value1 = exp1.getValue();
        System.out.println(value1);//3

        //例2：
        Expression exp2 = parser.parseExpression("T(System).getProperty('user.dir')");
        Object value2 = exp2.getValue();
        System.out.println(value2);//Users/hongshicheng/workspace/SpringBootStudy

        //例3：
        context.setVariable("user", new User("小花"));
        Expression exp3 = parser.parseExpression("#user.getName() + ' 你好！'");
        Object value3 = exp3.getValue(context);
        System.out.println(value3);//小花 你好！

        //例4：
        ParserContext parserContext =new TemplateParserContext();
        context.setVariable("person", new User("小草"));
        Expression exp4 = parser.parseExpression("#{#person.getName()} 你好！",parserContext);
        Object value4 = exp4.getValue(context);
        System.out.println(value4);//小草 你好！

        //例5：
        String[] students=new String[]{"tom","jack","rose","mark","lucy"};
        context.setVariable("students", students);
        Expression exp5 = parser.parseExpression("#students[3]");
        Object value5 = exp5.getValue(context);
        System.out.println(value5);//mark

    }

}
